import {vtdata} from "../../../database/vtdata.js";

export function Pagenator() {
    //在new之前,用户限制执行配置项
    if(!Pagenator.init){
        console.error('在实例化分页器之前,应当显执行Pagenator.config()');
        return ;
    }
    if(!Pagenator.renderInit){
        console.error('在实例化分页器之前,应当显执行Pagenator.renderInit()');
        return ;
    }

    Pagenator.self = this;
    this.total = Pagenator.total;
    this.pageShowNum = Pagenator.pageShowNum;
    this.btnNum = Pagenator.btnNum;
    this.totalPageNum = Math.ceil(this.total / this.pageShowNum);
    this.pageNumSelect = Pagenator.pageNumSelect;
    this.renderObject = Pagenator.renderObject;
    this.thePageNum = null;
    this.vtlistActive = null;
    this.goto = null;


    this.pagination = document.createElement("ul");
    this.pagination.className = "pagination ul-continar";
    this.createPageNumBtn();


    this.pagination.addEventListener("click", this.clickActive);
    this.clickActive(); //默认加载
}
/**
 * @total {number} - 传递一个总数据量
 * @pageShowNum {number} - 每一页默认显示多少数据
 * @btnNum {number} - 一共展示多少个分页按钮
 * @contianer {Dom-Object} - 放置的到什么容器中]
 * @pageNumSelect {Array} -每一个页面可以显示多少条数据 [5,10,15,20];
 * */
Pagenator.config = function ({
        total,
        pageShowNum,
        btnNum,
        pageNumSelect,
        contianer,
        renderObject,
        renderCallback,
        renderToDom
    }) {
    Pagenator.total = total;
    Pagenator.pageShowNum = pageShowNum;
    Pagenator.btnNum = btnNum;
    Pagenator.contianer = contianer;
    Pagenator.pageNumSelect = pageNumSelect;
    Pagenator.init = true; //证明Pagenator.config被调用了
}

Pagenator.setRender = function({renderObject,renderCallback,renderToDom,virtualCallback}){
    Pagenator.renderInit = true;
    Pagenator.renderObject = renderObject; //渲染对象
    Pagenator.renderCallback = renderCallback;
    Pagenator.renderToDom = renderToDom;
    Pagenator.virtualCallback = virtualCallback;
}

//静态方法
Pagenator.computeIndex = function (){
    var pageNow = parseInt(sessionStorage.getItem("pageNum") || "1");
    var startIndex = Pagenator.pageShowNum * (pageNow - 1);
    var endIndex = Pagenator.pageShowNum * pageNow - 1;

    return {//es6的简化对象
        startIndex,
        endIndex,
    }
}


//调用了以后,可以生成样式
Pagenator.createStyle = function () {
    return `       
            .page-item {
                user-select: none;
                cursor: pointer;
            }
            .vtlist-link {
                color : gray;
            }
            
            .vtlist-active {
                color : skyblue !important;
            }
            .li-goto {
                margin-left: 20px;
            }
            .li-goto input {
                width: 50px;height: 30px
            }
            .descrebtion {
                margin-right : 10px ;
                font-size: 16px;
                margin-left: 10%;
            }
            .descrebtion div{
                padding: 7px ;
            }
           
            .selector {
                margin-right : 20px ;
            }`
}



//总数据和总页码
Pagenator.prototype.totalInfo = function () {
    this.html += `<li class="descrebtion">
        <div>
            共${this.total}条数据; 共${this.totalPageNum}页;
        </div>
    </li>`;
}
//选择每一页显示多少条数据的
Pagenator.prototype.pageWithData = function () {
    this.html += `<li class="selector">
        <button class="btn dropdown-toggle" type="button" id="autoDirectionDropdown" data-bs-toggle="dropdown">
            ${this.pageShowNum}条/页
        </button>
        <ul class="dropdown-menu dropdown-defined-ul" >
      
        </ul>
    </li>`;
}
//上一页的按钮
Pagenator.prototype.prevPage = function () {
    this.html += `<li class="page-item" id="prevBtn">
        <a class="page-link"  id="Previous" aria-label="Previous">
            <span aria-hidden="true" id="prevSpan">&laquo;</span>
        </a>
     </li>
    `;
}
//页码
Pagenator.prototype.pageNum = function () {
    for (let i = 1; i <= this.totalPageNum; i++) {
        this.html += `<li class="page-item page-num" >
            <a class="page-link vtlist-link" data-page="${i}">
                ${i}
            </a>
         </li>`;
    }
}
//下一页的按钮
Pagenator.prototype.nextPage = function(){
    this.html += `<li class="page-item" id="nextBtn">
        <a class="page-link"  aria-label="Next" id="Next">
            <span aria-hidden="true" id="nextSpan">&raquo;</span>
        </a>
    </li>
    `
}
//前往多少页
Pagenator.prototype.gotoPage = function(){
    this.html += `<li class="li-goto">
          <span>前往:</span>
          <input type="text" id="goto" value="${this.thePageNum}">
          <span>/页</span>
     </li>
    `
}

Pagenator.prototype.selectPageNum = function () {

    var dropdownMenuWithPageNum = document.querySelector(".dropdown-defined-ul");

    var html = "";
    this.pageNumSelect.forEach(function(item){
        html +=`<li><a class="dropdown-item" href="javascript:;" data-num="${item}" >${item}条/页</a></li>`
    })
    dropdownMenuWithPageNum.innerHTML = html;
}

Pagenator.prototype.createPageNumBtn = function(){
    this.html = "";
    this.totalInfo();      //共xxx条数据
    this.pageWithData();   //下拉列表 替换页面显示数据数量
    this.prevPage();       //上一页
    this.pageNum();        //页码
    this.nextPage();       //下一页
    this.gotoPage();       //跳转页面
    this.pagination.innerHTML = this.html;   //把html放到ul中
    Pagenator.contianer.append(this.pagination);  //把ul放到div
    this.selectorEvent();    //下拉列表切换显示数量的事件
}

//开启js功能
Pagenator.prototype.selectorEvent = function (){

    this.selectPageNum();

    //下拉列表绑定事件
    var dropdownMenuWithPageNum = document.querySelector(".dropdown-defined-ul");
    var autoDirectionDropdown = document.querySelector("#autoDirectionDropdown");
    dropdownMenuWithPageNum.onclick = function(e){
        if(e.target.tagName === "A"){
            var num = e.target.getAttribute("data-num");
            Pagenator.self.pageShowNum = Pagenator.pageShowNum = num;
            autoDirectionDropdown.innerHTML = e.target.innerHTML;
            Pagenator.self.totalPageNum = Math.ceil(Pagenator.self.total / Pagenator.self.pageShowNum); //总页码数
            //当替换过一页显示多少条以后,需要对比 当前页码(11) 和 新的页码(7) 谁大
            //新的页码大 , 则不采取措施
            //当前页码大 , 则将sessionStorage中的页码替换为 新的页码的最后一页

            if(Pagenator.self.thePageNum > Pagenator.self.totalPageNum){
                Pagenator.self.thePageNum = Pagenator.self.totalPageNum;
                sessionStorage.setItem("pageNum", Pagenator.self.thePageNum);
            }

            Pagenator.self.createPageNumBtn(Pagenator.self.pagination);
            Pagenator.self.clickActive();

            //重新渲染数据
            if(Pagenator.self.renderObject){
                var inds = Pagenator.self.computeIndex(Pagenator.self.thePageNum);
                Pagenator.self.renderObject.setStartEndIndex(inds.startIndex,inds.endIndex);
                Pagenator.self.renderObject.createData(Pagenator.renderCallback,Pagenator.renderToDom);
            }

        }
    }

    this.goto = document.getElementById("goto");

    this.gotoEvent(this.goto);
}


Pagenator.prototype.gotoEvent = function (goto){
        goto.onfocus = function(e){
            var oldValue = e.target.value; //记录原来的页码

            window.onkeydown = function(event){
                if(event.key === "Enter"){
                    var intPage = parseInt(e.target.value);
                    if(Number.isNaN(intPage)){//是个NaN
                        e.target.value = oldValue;
                        return;
                    }

                    //传递进来的是个数字
                    if( !(intPage > 0 && intPage <= Pagenator.self.totalPageNum) ){

                        e.target.value = oldValue;
                        return;
                    }

                    //正常的
                    Pagenator.self.thePageNum = intPage;
                    sessionStorage.setItem("pageNum",  Pagenator.self.thePageNum);
                    var indexObj =  Pagenator.self.computeIndex( Pagenator.self.thePageNum);
                    //虚拟分页
                    var inds = Pagenator.self.computeIndex(Pagenator.self.thePageNum);
                    Pagenator.self.renderObject.setStartEndIndex(inds.startIndex,inds.endIndex);
                    Pagenator.self.renderObject.virtualUpdate(Pagenator.virtualCallback,Pagenator.renderToDom);
                    //修改字体的颜色
                    Pagenator.self.updateActive( Pagenator.self.thePageNum);
                    Pagenator.self.showPageBtn( Pagenator.self.thePageNum);

                    window.onkeydown = null;
                }
            }

            goto.onblur = function(e){
                window.onkeydown = goto.onblur = null;
            }
        }
    }



    Pagenator.prototype.showPageBtn = function (page=1){
        var links = document.querySelectorAll(".vtlist-link");
        links.forEach(function(link){
            link.style.display = "inline-block";
        })
        if(page === 1 || page === 2 ){ //前几页
            for(let i = this.btnNum; i < links.length; i++){
                links[i].style.display = "none";
            }

        }else if(page === links.length || page === links.length - 1){
            for(let i = links.length - this.btnNum -1; i > -1; i--){
                links[i].style.display = "none";
            }
        }else{
            for (let i = page -2 - 2; i > -1 ; i--) {
                links[i].style.display = "none";
            }
            for (let i = page + 2 ; i <  links.length; i++) {
                links[i].style.display = "none";
            }
        }
    }

    Pagenator.prototype.updateActive =  function (thePageNum) {
        this.vtlistActive?.classList.remove("vtlist-active");
        this.vtlistActive = document.querySelector(`[data-page="${thePageNum}"]`);
        this.vtlistActive.classList.add("vtlist-active");
    }

//点击左右 , 首次加载
Pagenator.prototype.clickActive = function (e) {

    var virtualSign  = true; //什么时候使用虚拟分页的信号量
    e?.preventDefault();
    if(e?.target.parentElement.classList.contains("page-num")){ //e.target 代表数字页码
        Pagenator.self.thePageNum = parseInt(e.target.getAttribute("data-page"));
        sessionStorage.setItem("pageNum", Pagenator.self.thePageNum);
    }else if(!e){  //e===undefined  首次加载
        if(!Pagenator.self.thePageNum) {
            if(sessionStorage.getItem("pageNum") === null){//为空
                Pagenator.self.thePageNum = 1;
                sessionStorage.setItem("pageNum", Pagenator.self.thePageNum);
            }else{//不为空
                Pagenator.self.thePageNum = parseInt(sessionStorage.getItem("pageNum"));
            }
        }
        virtualSign = false;
    }else if (e?.target.parentElement.id === "prevBtn"
        || e?.target.id === "Previous"
        || e?.target.id === "prevSpan"
    ){//向左
        if(Pagenator.self.thePageNum > 1){
            Pagenator.self.updateActive(--Pagenator.self.thePageNum);
            sessionStorage.setItem("pageNum", Pagenator.self.thePageNum);
        }
    }else if(
        e?.target.parentElement.id === "nextBtn"
        || e?.target.id === "Next"
        || e?.target.id === "nextSpan"
    ){
        if(Pagenator.self.thePageNum < Pagenator.self.totalPageNum){
            Pagenator.self.updateActive(++Pagenator.self.thePageNum);
            sessionStorage.setItem("pageNum", Pagenator.self.thePageNum);
        }

    }else{
        return;
    }

    var indexObj = Pagenator.self.computeIndex(Pagenator.self.thePageNum);

    if(virtualSign){
        var inds = Pagenator.self.computeIndex(Pagenator.self.thePageNum);
        Pagenator.self.renderObject.setStartEndIndex(inds.startIndex,inds.endIndex);
        Pagenator.self.renderObject.virtualUpdate(Pagenator.virtualCallback,Pagenator.renderToDom);
    }else{
        //显示数据的函数
        Pagenator.self.renderObject.createData(Pagenator.renderCallback,Pagenator.renderToDom);
    }

    Pagenator.self.goto.value = Pagenator.self.thePageNum;
    Pagenator.self.updateActive(Pagenator.self.thePageNum);
    Pagenator.self.showPageBtn(Pagenator.self.thePageNum);

}
//计算数据的起始索引 和 结束索引的
Pagenator.prototype.computeIndex = function (pageNow){
    var startIndex = this.pageShowNum * (pageNow - 1);
    var endIndex = this.pageShowNum * pageNow - 1;

    return {//es6的简化对象
        startIndex,
        endIndex,
    }
}

//实例对象设置属性
Pagenator.prototype.setPropertys = function({total,thePageNum}){
    this.total = total;
    this.thePageNum = thePageNum;
    this.totalPageNum = Math.ceil(this.total / this.pageShowNum);
    sessionStorage.setItem("pageNum", this.thePageNum);
}




